<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据表格 - 转换型</title>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/layui@2.6.8/dist/css/layui.css">
    <script src="//cdn.jsdelivr.net/npm/layui@2.6.8/dist/layui.js" charset="utf-8"></script>
</head>

<body>
    <div style="margin: 15px;padding:15px;background-color: #fff;">
        <!-- 头工具栏 -->
        <div class="layui-form">
            <div class="layui-inline" style="float: right;">
                <div class="layui-input-inline">
                    <input type="text" name="meta_key|meta_value" value="<?=$search['meta_key|meta_value'] ?? ''?>"
                        placeholder="键或值" class="layui-input" style="height: 30px;">
                </div>
                <button class="layui-btn layui-btn-primary layui-btn-sm" lay-submit lay-filter="search"><i
                        class="layui-icon layui-icon-search"></i></button>
            </div>

            <div class="layui-inline">
                <div class="layui-btn-group">
                    <button class="layui-btn layui-btn-sm" lay-event="delAll">批量删除</button>
                    <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
                    <button class="layui-btn layui-btn-sm" lay-event="refresh"><i
                            class="layui-icon layui-icon-refresh"></i></button>
                </div>
            </div>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" lay-filter="parseTable" id="parseTable">
            <thead>
                <tr>
                    <th lay-data="{checkbox:true, fixed: 'left'}"></th>
                    <th lay-data="{field:'id', width:80, sort: true}">ID</th>
                    <th lay-data="{field:'meta_key', edit: 'text'}">键（编辑）</th>
                    <th lay-data="{field:'meta_value', event: 'meta_value', style: 'cursor: pointer;'}">值（输入层）</th>
                    <th lay-data="{field:'status', sort: true, templet:'#statusTpl', width: 95}">状态</th>
                    <th lay-data="{field:'time'}">时间</th>
                    <th lay-data="{width:120, align:'center', toolbar: '#databar'}">操作</th>
                </tr>
            </thead>

            <tbody>
                {foreach $items as $item}
                <tr>
                    <td></td>
                    <td>{$item['id']}</td>
                    <td>{$item['meta_key']}</td>
                    <td>{$item['meta_value']}</td>
                    <td>{$item['status']}</td>
                    <td>{$item['time']}</td>
                    <td></td>
                </tr>
                {/foreach}
            </tbody>
        </table>

        <!-- 分页 -->
        <div id="pages"></div>

        <!-- 行工具 -->
        <script type="text/html" id="databar">
            <a class="layui-btn layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>

        <!-- 单元格状态开关 -->
        <script type="text/html" id="statusTpl">
            <input type="checkbox" name="status" lay-filter="status" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" {{# if(d.status == 0){ }} checked{{# } }}>
        </script>

    </div>

    <!-- js -->
    <script>
        layui.use(['form', 'table', 'laypage', 'util'], function () {
            var form = layui.form,
                table = layui.table,
                laypage = layui.laypage,
                util = layui.util,
                $ = layui.jquery;

            // 获取应用、控制器和方法
            var module = '{:app("http")->getName()}'
                , controller = '{$Request.controller}'
                , action = '{$Request.action}';

            // 分页
            laypage.render({
                elem: 'pages',
                count: '{$total}',
                limit: '{$pageSize}',
                curr: '{$page}',
                layout: ['prev', 'page', 'next', 'limit'],
                jump: function (obj, first) {
                    if (!first) {
                        window.location.href = '?page=' + obj.curr + '&limit=' + obj.limit;
                    }
                }
            });

            // 转换表格
            table.init('parseTable', {
                height: 'full',
                limit: '{$pageSize}',
            });

            // 头工具事件
            util.event('lay-event', {
                // 头工具批量删除
                delAll: function (othis) {
                    var checkStatus = table.checkStatus('parseTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        return layer.msg('请选择数据');
                    }
                    layer.confirm('确定删除吗？', { icon: 3 }, function (index) {
                        var ids = [];
                        data.forEach(elem => { ids.push(elem.id); });
                        $.post('/' + module + '/' + controller + '/del', { id: ids }, function (res) {
                            if (res.code) return layer.msg(res.msg, { icon: 2 });
                            layer.msg(res.msg);
                            window.location.reload();
                        }, 'json');
                    });
                },

                // 头工具添加
                add: function (othis) {
                    layer.open({
                        type: 2,
                        maxmin: true,
                        title: '添加',
                        shadeClose: true,
                        shade: 0.3,
                        area: $(window).width() <= 480 ? ['95%', '80%'] : ['480px', '450px'],
                        content: '/' + module + '/' + controller + '/add',
                    });
                },

                // 头工具刷新
                refresh: function (othis) {
                    window.location.reload();
                },

            });

            // 监听行工具事件
            table.on('tool(parseTable)', function (obj) {
                var data = obj.data;

                // 行工具删除行
                if (obj.event === 'del') {
                    layer.confirm('真的删除行么？', { icon: 3 }, function (index) {
                        layer.close(index);
                        $.post('/' + module + '/' + controller + '/del', { id: data.id }, function (res) {
                            if (res.code) return layer.msg(res.msg, { icon: 2 });
                            obj.del();
                            layer.msg(res.msg);
                        }, 'json');
                    });
                }

                // 行工具当前添加
                else if (obj.event === 'add') {
                    layer.open({
                        type: 2,
                        title: '添加',
                        shadeClose: true,
                        shade: 0.3,
                        area: $(window).width() <= 480 ? ['95%', '80%'] : ['480px', '450px'],
                        content: '/' + module + '/' + controller + '/add?id=' + data.id,
                    });
                }

                // 行工具编辑行
                else if (obj.event === 'edit') {
                    layer.open({
                        type: 2,
                        maxmin: true,
                        title: '编辑',
                        shadeClose: true,
                        shade: 0.3,
                        area: $(window).width() <= 480 ? ['95%', '80%'] : ['480px', '450px'],
                        content: '/' + module + '/' + controller + '/edit?id=' + data.id,
                    });
                }

                // 行工具单元格事件
                else if (obj.event === 'meta_value') {
                    layer.prompt({
                        formType: 2 //支持0（文本）默认1（密码）2（多行文本）
                        , title: '修改值（输入层）' //标题
                        , value: data.meta_value
                    }, function (value, index) {
                        $.post('/' + module + '/' + controller + '/modify', { id: data.id, field: 'meta_value', value: value }, function (res) {
                            if (res.code) return layer.msg(res.msg, { icon: 2 });
                            layer.close(index);
                            // 同步更新缓存对应的值
                            obj.update({
                                meta_value: value
                            });
                            layer.msg(res.msg, { icon: 1 });
                        }, 'json');
                    });
                }

                // 行工具详情页
                else if (obj.event === 'detail') {
                    window.open('/' + controller + '/' + (typeof data.slug !== 'undefined' ? data.slug : data.id) + '.html', '_blank');
                }

                // 行工具跳转
                else if (obj.event) {
                    window.location.href = '/' + module + '/' + controller + '/' + obj.event + '?id=' + data.id;
                }
            });

            // 监听单元格编辑
            table.on('edit(parseTable)', function (obj) {
                var value = obj.value //得到修改后的值
                    , data = obj.data //得到所在行所有键值
                    , field = obj.field; //得到字段
                $.post('/' + module + '/' + controller + '/modify', { id: data.id, field: field, value: util.escape(value) }, function (res) {
                    if (res.code) {
                        layer.alert(res.msg, { icon: 2 });
                        setTimeout(() => window.location.reload(), 1000);
                        return;
                    }
                    layer.msg(res.msg);
                }, 'json');
            });

            // 列表开关事件
            form.on('switch(status)', function (obj) {
                $.post('/' + module + '/' + controller + '/modify', { id: obj.value, field: 'status', value: obj.elem.checked ? 0 : 1 }, function (res) {
                    if (res.code) {
                        layer.alert(res.msg, { icon: 2 });
                        setTimeout(() => window.location.reload(), 1000);
                        return;
                    }
                    layer.msg(res.msg);
                }, 'json');
            });

            // 搜索框事件
            form.on('submit(search)', function (obj) {
                var data = obj.field;
                var search_str = '';
                for (var key in data) {
                    if (search_str.length) search_str += '&';
                    search_str += 'search[' + key + ']=' + data[key];
                }
                window.location.href = '?' + search_str;
            })

        });

    </script>

</body>

</html>